package com.wandousoushu.jiusen.ui.book.read

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.util.Base64
import android.view.*
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.webkit.DownloadListener
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import com.jaredrummler.android.colorpicker.ColorPickerDialogListener
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.base.VMBaseActivity
import com.wandousoushu.jiusen.booksource.bean.BookChapter
import com.wandousoushu.jiusen.booksource.constant.EventBus
import com.wandousoushu.jiusen.booksource.constant.PreferKey
import com.wandousoushu.jiusen.booksource.constant.Status
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.data.entities.ReadBook
import com.wandousoushu.jiusen.help.ReadBookConfig
import com.wandousoushu.jiusen.lib.dialogs.alert
import com.wandousoushu.jiusen.lib.dialogs.noButton
import com.wandousoushu.jiusen.lib.dialogs.okButton
import com.wandousoushu.jiusen.lib.theme.ATH
import com.wandousoushu.jiusen.receiver.TimeBatteryReceiver
import com.wandousoushu.jiusen.service.BaseReadAloudService
import com.wandousoushu.jiusen.ui.book.changesource.ChangeSourceDialog
import com.wandousoushu.jiusen.ui.book.chapterlist.ChapterListActivity
import com.wandousoushu.jiusen.ui.book.read.config.BgTextConfigDialog
import com.wandousoushu.jiusen.ui.book.read.config.BgTextConfigDialog.Companion.BG_COLOR
import com.wandousoushu.jiusen.ui.book.read.config.BgTextConfigDialog.Companion.TEXT_COLOR
import com.wandousoushu.jiusen.ui.book.read.config.PaddingConfigDialog
import com.wandousoushu.jiusen.ui.book.read.config.ReadStyleDialog
import com.wandousoushu.jiusen.ui.book.read.page.ContentTextView
import com.wandousoushu.jiusen.ui.book.read.page.PageView
import com.wandousoushu.jiusen.ui.book.read.page.TextPageFactory
import com.wandousoushu.jiusen.ui.book.read.page.delegate.PageDelegate
import com.wandousoushu.jiusen.ui.login.LoginActivity
import com.wandousoushu.jiusen.util.*
import kotlinx.android.synthetic.main.activity_book_read.*
import kotlinx.android.synthetic.main.layout_read_title_bar.*
import kotlinx.android.synthetic.main.view_read_menu.*
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import org.jetbrains.anko.sdk27.listeners.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult


class ReadBookActivity : VMBaseActivity<ReadBookViewModel>(R.layout.activity_book_read),
        View.OnTouchListener,
        PageView.CallBack,
        TextActionMenu.CallBack,
        ContentTextView.CallBack,
        ReadMenu.CallBack,
        ReadBook.CallBack,
        ChangeSourceDialog.CallBack,
        ColorPickerDialogListener {
    private val requestCodeChapterList = 568
    private val requestCodeEditSource = 111
    private val requestCodeReplace = 312
    private var menu: Menu? = null
    private var textActionMenu: TextActionMenu? = null
    private var isDownload = true
    override val viewModel: ReadBookViewModel get() = getViewModel(ReadBookViewModel::class.java)
    override val isInitFinish: Boolean get() = viewModel.isInitFinish
    private val mHandler = Handler()
    private val keepScreenRunnable: Runnable = Runnable { Help.keepScreenOn(window, false) }
    private val autoPageRunnable: Runnable = Runnable { autoPagePlus() }
    override var autoPageProgress = 0
    override var isAutoPage = false
    private var screenTimeOut: Long = 0
    private var timeBatteryReceiver: TimeBatteryReceiver? = null
    override val pageFactory: TextPageFactory get() = page_view.pageFactory
    override val headerHeight: Int get() = page_view.curPage.headerHeight
    override fun onCreate(savedInstanceState: Bundle?) {
        ReadBook.msg = null
        Help.setOrientation(this)
        super.onCreate(savedInstanceState)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        Help.upLayoutInDisplayCutoutMode(window)
        initView()
        upScreenTimeOut()
        ReadBook.callBack = this
        ReadBook.titleDate.observe(this, Observer {
            //title_bar.title = it
            tv_read_bar_title.text = it
            //upMenu()
            upView()
        })
        viewModel.initData(intent)
    }
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        upSystemUiVisibility()
    }
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        ReadBook.loadContent(resetPageOffset = false)
    }
    override fun onResume() {
        super.onResume()
        upSystemUiVisibility()
        timeBatteryReceiver = TimeBatteryReceiver.register(this)
        page_view.upTime()
    }
    override fun onPause() {
        super.onPause()
        ReadBook.saveRead()
        timeBatteryReceiver?.let {
            unregisterReceiver(it)
            timeBatteryReceiver = null
        }
        upSystemUiVisibility()
//        if (!BuildConfig.DEBUG) {
//            SyncBookProgress.uploadBookProgress()
//            Backup.autoBack(this)
//        }
    }
    override fun upNavigationBarColor() {
        when {
            read_menu == null -> return
            read_menu.isVisible -> {
                ATH.setNavigationBarColorAuto(this)
            }
            ReadBookConfig.bg is ColorDrawable -> {
                ATH.setNavigationBarColorAuto(this, ReadBookConfig.bgMeanColor)
            }
            else -> {
                ATH.setNavigationBarColorAuto(this, Color.BLACK)
            }
        }
    }
    /**
     * 初始化View
     */
    private fun initView() {
//        cursor_left.setColorFilter(accentColor)
//        cursor_right.setColorFilter(accentColor)
//        cursor_left.setOnTouchListener(this)
//        cursor_right.setOnTouchListener(this)

        tv_chapter_url.onClick {
            runCatching {
                val url = tv_chapter_url.text.toString()
                startActivity<ReadOriginActivity>(
                        Pair("bookUrl", url)
                )
            }
        }

        tv_read_bar_change.onClick {
            read_menu.runMenuOut()
            ReadBook.book?.let {
                ChangeSourceDialog.show(supportFragmentManager, it.name, it.author)
            }
        }
        if (MyApplication.instance.isVip) {
            ad_h5_webview.gone()
        } else {
            ad_h5_webview.visible()
            SetPageAd()
        }
    }
    fun showPaddingConfig() {
        PaddingConfigDialog().show(supportFragmentManager, "paddingConfig")
    }
    fun showBgTextConfig() {
        BgTextConfigDialog().show(supportFragmentManager, "bgTextConfig")
    }
    /**
     * 按键拦截,显示菜单
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val keyCode = event?.keyCode
        val action = event?.action
        val isDown = action == 0

        if (keyCode == KeyEvent.KEYCODE_MENU) {
//            if (isDown && !read_menu.cnaShowMenu) {
//                read_menu.runMenuIn()
//                return true
//            }
//            if (!isDown && !read_menu.cnaShowMenu) {
//                read_menu.cnaShowMenu = true
//                return true
//            }
        }
        return super.dispatchKeyEvent(event)
    }
    /**
     * 按键事件
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            getPrefInt(PreferKey.prevKey) -> {
                if (keyCode != KeyEvent.KEYCODE_UNKNOWN) {
                    page_view.pageDelegate?.keyTurnPage(PageDelegate.Direction.PREV)
                    return true
                }
            }
            getPrefInt(PreferKey.nextKey) -> {
                if (keyCode != KeyEvent.KEYCODE_UNKNOWN) {
                    page_view.pageDelegate?.keyTurnPage(PageDelegate.Direction.NEXT)
                    return true
                }
            }
            KeyEvent.KEYCODE_VOLUME_UP -> {
                if (volumeKeyPage(PageDelegate.Direction.PREV)) {
                    return true
                }
            }
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                if (volumeKeyPage(PageDelegate.Direction.NEXT)) {
                    return true
                }
            }
            KeyEvent.KEYCODE_SPACE -> {
                page_view.pageDelegate?.keyTurnPage(PageDelegate.Direction.NEXT)
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }
    /**
     * 长按事件
     */
    override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                finish()
                return true
            }
        }
        return super.onKeyLongPress(keyCode, event)
    }
    /**
     * 松开按键事件
     */
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN -> {
                if (volumeKeyPage(PageDelegate.Direction.NONE)) {
                    return true
                }
            }
            KeyEvent.KEYCODE_BACK -> {
                event?.let {
                    if ((event.flags and KeyEvent.FLAG_CANCELED_LONG_PRESS == 0) && event.isTracking && !event.isCanceled) {
//
                    }
                }
            }
        }
        return super.onKeyUp(keyCode, event)
    }
    /**
     * view触摸
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> textActionMenu?.dismiss()
            MotionEvent.ACTION_MOVE -> {
                when (v.id) {
                    R.id.cursor_left -> page_view.curPage.selectStartMove(
                            event.rawX + cursor_left.width,
                            event.rawY - cursor_left.height
                    )
                    R.id.cursor_right -> page_view.curPage.selectEndMove(
                            event.rawX - cursor_right.width,
                            event.rawY - cursor_right.height
                    )
                }
            }
            MotionEvent.ACTION_UP -> showTextActionMenu()
        }
        return true
    }
    /**
     * 更新文字选择开始位置
     */
    override fun upSelectedStart(x: Float, y: Float, top: Float) {
        cursor_left.x = x - cursor_left.width
        cursor_left.y = y
        cursor_left.visible(true)
        text_menu_position.x = x
        text_menu_position.y = top
    }
    /**
     * 更新文字选择结束位置
     */
    override fun upSelectedEnd(x: Float, y: Float) {
        cursor_right.x = x
        cursor_right.y = y
        cursor_right.visible(true)
    }
    /**
     * 取消文字选择
     */
    override fun onCancelSelect() {
        cursor_left.invisible()
        cursor_right.invisible()
        textActionMenu?.dismiss()
    }
    /**
     * 显示文本操作菜单
     */
    override fun showTextActionMenu() {
        textActionMenu ?: let {
            textActionMenu = TextActionMenu(this, this)
        }
        textActionMenu?.let { popup ->
            popup.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val popupHeight = popup.contentView.measuredHeight
            val x = text_menu_position.x.toInt()
            var y = text_menu_position.y.toInt() - popupHeight
            if (y < statusBarHeight) {
                y = (cursor_left.y + cursor_left.height).toInt()
            }
            if (cursor_right.y > y && cursor_right.y < y + popupHeight) {
                y = (cursor_right.y + cursor_right.height).toInt()
            }
            if (!popup.isShowing) {
                popup.showAtLocation(text_menu_position, Gravity.TOP or Gravity.START, x, y)
            } else {
                popup.update(x, y, WRAP_CONTENT, WRAP_CONTENT)
            }
        }
    }
    /**
     * 音量键翻页
     */
    private fun volumeKeyPage(direction: PageDelegate.Direction): Boolean {
        if (!read_menu.isVisible) {
            if (getPrefBoolean("volumeKeyPage", true)) {
                if (getPrefBoolean("volumeKeyPageOnPlay")
                        || BaseReadAloudService.pause
                ) {
                    page_view.pageDelegate?.isCancel = false
                    page_view.pageDelegate?.keyTurnPage(direction)
                    return true
                }
            }
        }
        return false
    }
    /**
     * 内容加载完成
     */
    override fun contentLoadFinish() {
//        if (intent.getBooleanExtra("readAloud", false)) {
//            intent.removeExtra("readAloud")
//            ReadBook.readAloud()
//        }
    }
    /**
     * 更新内容
     */
    override fun upContent(relativePosition: Int, resetPageOffset: Boolean) {
        autoPageProgress = 0
        launch {
            page_view.upContent(relativePosition, resetPageOffset)
            seek_read_page.progress = ReadBook.durPageIndex
        }
    }
    /**
     * 更新视图
     */
    override fun upView() {
        launch {
            ReadBook.curTextChapter?.let {
                tv_chapter_name.text = it.title
                tv_chapter_name.visible()
                if (!ReadBook.isLocalBook) {
                    tv_chapter_url.text = it.url
                    tv_chapter_url.visible()
                } else {
                    tv_chapter_url.gone()
                }
                seek_read_page.max = it.pageSize.minus(1)
                seek_read_page.progress = ReadBook.durPageIndex
                tv_pre.isEnabled = ReadBook.durChapterIndex != 0
                tv_next.isEnabled = ReadBook.durChapterIndex != ReadBook.chapterSize - 1
            } ?: let {
                tv_chapter_name.gone()
                tv_chapter_url.gone()
            }
        }
    }
    /**
     * 页面改变
     */
    override fun pageChanged() {
        autoPageProgress = 0
        launch {
            seek_read_page.progress = ReadBook.durPageIndex
        }
    }
    override fun clickCenter() {
        when {
            BaseReadAloudService.isRun -> {
                showReadAloudDialog()
            }
            isAutoPage -> {
                //AutoReadDialog().show(supportFragmentManager, "autoRead")
                read_menu.runMenuIn()
            }
            else -> {
                read_menu.runMenuIn()
            }
        }
    }
    private fun SetPageAd() {
        if (MyApplication.instance.pageH5 == null) return
        this.runOnUiThread(Runnable {
            ad_h5_webview.getSettings().javaScriptEnabled = true
            ad_h5_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true)
            ad_h5_webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            ad_h5_webview.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
            ad_h5_webview.getSettings().setAppCacheEnabled(true);//是否使用缓存
            ad_h5_webview.getSettings().setDomStorageEnabled(true);//DOM Storage
            val webClient = object : WebViewClient() {
//                override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) {
//                    handler.proceed() // 接受所有网站的证书
//                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    if (url!!.startsWith("http")) {
                        try {
                            val intent = Intent()
                            intent.action = Intent.ACTION_VIEW
                            val content_url = Uri.parse(url) //此处填链接
                            intent.data = content_url
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                            startActivity(intent)
                            isDownload = false
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                        return true
                    }
                    return false
                }
            }
            ad_h5_webview.setWebViewClient(webClient)
//            ad_h5_webview.setWebViewClient(WebViewClient())
            ad_h5_webview.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
                if (isDownload) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    val content_url = Uri.parse(url) //此处填链接
                    intent.addCategory(Intent.CATEGORY_BROWSABLE)
                    intent.data = content_url
                    startActivity(intent)
                }
                isDownload = true
            })
            try {
//                var newhtml_code = Base64.encodeToString(MyApplication.instance.pageH5!!.htmladvert.encodeToByteArray(), Base64.NO_PADDING)
//                ad_h5_webview.loadData(newhtml_code, "text/html", "base64")
                ad_h5_webview.loadDataWithBaseURL(null, MyApplication.instance.pageH5!!.htmladvert, "text/html", "utf-8", null)
            } catch (e: Exception) {
                e.printStackTrace()
            }

        })
    }
    private fun autoPagePlus() {
        mHandler.removeCallbacks(autoPageRunnable)
        autoPageProgress++
        if (autoPageProgress >= ReadBookConfig.autoReadSpeed * 10) {
            autoPageProgress = 0
            page_view.fillPage(PageDelegate.Direction.NEXT)
        } else {
            page_view.invalidate()
        }
        mHandler.postDelayed(autoPageRunnable, 100)
    }
    override fun autoPage() {
        TODO("Not yet implemented")
    }
    override fun openReplaceRule() {
        TODO("Not yet implemented")
    }
//    /**
//     * 替换
//     */
//    override fun openReplaceRule() {
//        startActivityForResult<ReplaceRuleActivity>(requestCodeReplace)
//    }

    /**
     * 打开目录
     */
    override fun openChapterList() {
        ReadBook.book?.let {
            startActivityForResult<ChapterListActivity>(
                    requestCodeChapterList,
                    Pair("bookUrl", it.bookUrl)
            )
        }
    }
    override fun showMoreSetting() {
        TODO("Not yet implemented")
    }
    override fun showReadAloudDialog() {
        TODO("Not yet implemented")
    }
//    /**
//     * 替换规则变化
//     */
//    override fun onReplaceRuleSave() {
//        Coroutine.async {
//            BookHelp.upReplaceRules()
//            ReadBook.loadContent(resetPageOffset = false)
//        }
//    }

    /**
     * 显示阅读样式配置
     */
    override fun showReadStyle() {
        ReadStyleDialog().show(supportFragmentManager, "readStyle")
    }
//
//    /**
//     * 显示更多设置
//     */
//    override fun showMoreSetting() {
//        MoreConfigDialog().show(supportFragmentManager, "moreConfig")
//    }

    /**
     * 更新状态栏,导航栏
     */
    override fun upSystemUiVisibility() {
        Help.upSystemUiVisibility(this, !read_menu.isVisible)
        upNavigationBarColor()
    }
    /**
     * 朗读按钮
     */
    override fun onClickReadAloud() {
//        when {
//            !BaseReadAloudService.isRun -> ReadBook.readAloud()
//            BaseReadAloudService.pause -> ReadAloud.resume(this)
//            else -> ReadAloud.pause(this)
//        }
    }
    /**
     * colorSelectDialog
     */
    override fun onColorSelected(dialogId: Int, color: Int) = with(ReadBookConfig.durConfig) {
        when (dialogId) {
            TEXT_COLOR -> {
                setTextColor(color)
                postEvent(EventBus.UP_CONFIG, false)
            }
            BG_COLOR -> {
                setBg(0, "#${color.hexString}")
                ReadBookConfig.upBg()
                postEvent(EventBus.UP_CONFIG, false)
            }
        }
    }

    /**
     * colorSelectDialog
     */
    override fun onDialogDismissed(dialogId: Int) = Unit
//    override fun onTocRegexDialogResult(tocRegex: String) {
//        ReadBook.book?.let {
//            it.tocUrl = tocRegex
//            viewModel.loadChapterList(it)
//        }
//    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                requestCodeEditSource -> viewModel.upBookSource()
                requestCodeChapterList ->
                    data?.getIntExtra("index", ReadBook.durChapterIndex)?.let { index ->
                        if (index != ReadBook.durChapterIndex) {
                            viewModel.openChapter(index)
                        }
                    }
//                requestCodeReplace -> onReplaceRuleSave()
            }
        }
    }
    override fun finish() {
        ReadBook.book?.let {
            if (!ReadBook.inBookshelf) {
                this.alert(title = getString(R.string.add_to_shelf)) {
                    message = getString(R.string.check_add_bookshelf, it.name)
                    okButton {
                        if (MyApplication.instance.isLogin) {
                            ReadBook.inBookshelf = true
                            val data = Intent()
                            data.putExtra("bookurl", ReadBook.book!!.bookUrl)
                            setResult(Activity.RESULT_OK, data)
                        } else {
                            startActivity<LoginActivity>()
                        }
                        super.finish()
                    }
                    noButton { viewModel.removeFromBookshelf { super.finish() } }
                }.show().applyTint()
            } else {
                super.finish()
            }
        } ?: super.finish()
    }
    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacks(keepScreenRunnable)
        textActionMenu?.dismiss()
        page_view.onDestroy()
        ReadBook.msg = null
        ad_h5_webview.stopLoading()
        ad_h5_webview.removeAllViews()
        ad_h5_webview.destroy()
//        if (!BuildConfig.DEBUG) {
//            SyncBookProgress.uploadBookProgress()
//            Backup.autoBack(this)
//        }
    }
    override fun observeLiveBus() {
        super.observeLiveBus()
        observeEvent<String>(EventBus.TIME_CHANGED) { page_view.upTime() }
        observeEvent<Int>(EventBus.BATTERY_CHANGED) { page_view.upBattery(it) }
        observeEvent<BookChapter>(EventBus.OPEN_CHAPTER) {
            viewModel.openChapter(it.index, ReadBook.durPageIndex)
            page_view.upContent()
        }
//        observeEvent<Boolean>(EventBus.MEDIA_BUTTON) {
//            if (it) {
//                onClickReadAloud()
//            } else {
//                ReadBook.readAloud(!BaseReadAloudService.pause)
//            }
//        }
        observeEvent<Boolean>(EventBus.UP_CONFIG) {
            upSystemUiVisibility()
            page_view.upBg()
            page_view.upTipStyle()
            page_view.upStyle()
            if (it) {
                ReadBook.loadContent(resetPageOffset = false)
            } else {
                page_view.upContent(resetPageOffset = false)
            }
        }
        observeEvent<Int>(EventBus.ALOUD_STATE) {
            if (it == Status.STOP || it == Status.PAUSE) {
                ReadBook.curTextChapter?.let { textChapter ->
                    val page = textChapter.page(ReadBook.durPageIndex)
                    if (page != null) {
                        page.removePageAloudSpan()
                        page_view.upContent(resetPageOffset = false)
                    }
                }
            }
        }
        observeEventSticky<Int>(EventBus.TTS_PROGRESS) { chapterStart ->
            launch(IO) {
                if (BaseReadAloudService.isPlay()) {
                    ReadBook.curTextChapter?.let { textChapter ->
                        val pageStart =
                                chapterStart - textChapter.getReadLength(ReadBook.durPageIndex)
                        textChapter.page(ReadBook.durPageIndex)?.upPageAloudSpan(pageStart)
                        upContent()
                    }
                }
            }
        }
        observeEvent<Boolean>(PreferKey.keepLight) {
            upScreenTimeOut()
        }
        observeEvent<Boolean>(PreferKey.textSelectAble) {
            page_view.curPage.upSelectAble(it)
        }
        observeEvent<String>(PreferKey.showBrightnessView) {
            read_menu.upBrightnessState()
        }
    }
    private fun upScreenTimeOut() {
        getPrefString(PreferKey.keepLight)?.let {
            screenTimeOut = it.toLong() * 1000
        }
        screenOffTimerStart()
    }
    /**
     * 重置黑屏时间
     */
    override fun screenOffTimerStart() {
        if (screenTimeOut < 0) {
            Help.keepScreenOn(window, true)
            return
        }
        val t = screenTimeOut - sysScreenOffTime
        if (t > 0) {
            mHandler.removeCallbacks(keepScreenRunnable)
            Help.keepScreenOn(window, true)
            mHandler.postDelayed(keepScreenRunnable, screenTimeOut)
        } else {
            Help.keepScreenOn(window, false)
        }
    }
    override val selectedText: String get() = TODO("Not yet implemented")
    override fun onMenuItemSelected(itemId: Int): Boolean {
        TODO("Not yet implemented")
    }
    override fun onMenuActionFinally() {
        TODO("Not yet implemented")
    }
    override val oldBook: Book? get() = ReadBook.book
    override fun changeTo(book: Book) {
        viewModel.changeTo(book)
    }
}